package com.DreamForce.Demo.common.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipHandler {
	
	private ZipOutputStream zos;
	 private FileInputStream fis;

	 // 在当前条目中写入具体内容
	 public void writeToEntryZip(String filePath) 
	 {
	  try
	  {
	   fis = new FileInputStream(filePath);
	  } catch (FileNotFoundException e1) 
	  {
	   e1.printStackTrace();
	  }
	  byte[] buff = new byte[1024];
	  int len = 0;
	  try 
	  {
	   while ((len = fis.read(buff)) != -1)
	   {
	    zos.write(buff, 0, len);
	   }
	  } catch (IOException e) 
	  {
	   e.printStackTrace();
	  }finally
	  {
	   if (fis != null)
	   try 
	   {
	     fis.close();
	   } catch (IOException e) 
	   {
	     e.printStackTrace();
	   }
	  }
	 }

	 // 添加文件条目
	 public void addFileEntryZip(String fileName) 
	 {
	  try 
	  {
	   zos.putNextEntry(new ZipEntry(fileName));
	  } catch (IOException e) 
	  {
	   e.printStackTrace();
	  }
	 }

	 public void addDirectoryEntryZip(String directoryName)
	 {
	  try 
	  {
	   zos.putNextEntry(new ZipEntry(directoryName + "/"));
	  } catch (IOException e)
	  {
	   e.printStackTrace();
	  }
	 }

	 // 遍历文件夹
	 public void listMyDirectory(String filePath)
	 {
	  File f = new File(filePath);
	  File[] files = f.listFiles();
	  if(files!=null)
	  {
	   for (File currentFile : files) 
	   {
	    // 设置条目名称(此步骤非常关键)
	    String entryName= currentFile.getAbsolutePath().split(":")[1].substring(1);
	    // 获取文件物理路径
	    String absolutePath = currentFile.getAbsolutePath();
	    if (currentFile.isDirectory()) 
	    {
	     addDirectoryEntryZip(entryName);
	     //进行递归调用
	     listMyDirectory(absolutePath);
	    
	    }
	    else 
	    {
	     addFileEntryZip(entryName);
	     writeToEntryZip(absolutePath);
	    }
	   }
	  }
	 }

	 // 主要流程
	 public boolean mainWorkFlow(String sourceFilePath,String currentZipFilePath)
	 {
		try {
			zos = new ZipOutputStream(new FileOutputStream(currentZipFilePath));
			zos.setLevel(9);
			listMyDirectory(sourceFilePath);
			if (zos != null)
				zos.close();
		} catch (Exception e) {
			return false;
		}

	    return true;
	} 

}
